package com.tckj.boot.modules.domain.sys.dict;

import com.tckj.boot.common.utils.BeanUtils;
import com.tckj.boot.common.utils.QueryHelp;
import com.tckj.boot.modules.domain.sys.dict.dto.DictDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
* @author icodebug
* @date 2019-07-08
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictService {

    @Autowired
    private DictRepository dictRepository;


    public Object queryAll(DictDTO dict, Pageable pageable){
        Page<Dict> page = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb), pageable);
        return page;
    }

    public Dict findById(Long id) {
        Optional<Dict> dict = dictRepository.findById(id);
        return dict.get();
    }

    @Transactional(rollbackFor = Exception.class)
    public Dict create(Dict resources) {
        return dictRepository.save(resources);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(Dict resources) {
        Optional<Dict> optionalDict = dictRepository.findById(resources.getId());
        if (optionalDict.isPresent()){
            Dict dict = optionalDict.get();
            BeanUtils.copyNotNullProperties(resources,dict);
            dictRepository.save(dict);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        dictRepository.deleteById(id);
    }
}